import string
import time
from tools import config
from tools import alert
from db.mysql import *
import logging

logging.basicConfig (level = logging.DEBUG, format = "%(created)-15s %(msecs)d %(levelname)8s %(thread)d %(name)s %(message)s")
log = logging.getLogger (__name__)

class ParserClass :
	def __init__ (self, nodes_and_stuff) :
		""" """
		self.debug = config.getDebug ()
		if self.debug :
			log.debug ("__init__")
		self.nodes = nodes_and_stuff
		self.db = DBConn()

	def parsemsg(self, msg, sock, nodename):
		""" """
		if self.debug :
			log.debug ("parsemsg")
		m=list(string.split(msg,"|"))
		mhead=list(string.split(m.pop(0)," "))
		if mhead[0] == "alert" and len (mhead) >= 3 :
			alertmsg = ""
			for mm in mhead[2:] :
				alertmsg += str (mm)
			alert.handle_alert (nodename, mhead[1], alertmsg)
			return
	
		elif mhead[0] == "hi" :
			try :
				i = self.nodes[0].index (nodename)
				for j in self.nodes[3][0][i] :
					k = self.nodes[3][0][i].index (j)
					self.nodes[3][1][i][k] = 0
			except ValueError :
				return
			return
	
		elif mhead[0] == "re" :
			return
	
		elif mhead[0] == "reply" :
			if len (m) == 0 :
				pl = mhead[1]
				try :
					nodeno = self.nodes[0].index (nodename)
					plno = self.nodes[2][nodeno].index (pl)
				except ValueError :
					return
				val = string.join (mhead[2:], " ")
				self.db.insert(nodename, pl, time.time(), val)
				return

			else :
				pl = mhead[1]
				if nodename in self.nodes[0] :
					nodeno = self.nodes[0].index (nodename)
				else :
					return
				if pl in self.nodes[3][0][nodeno] :
					plno = self.nodes[3][0][nodeno].index (pl)
				else :
					return
				val = []
				while not len (m) == 0 :
					t = list (string.split (m.pop(0), " "))
					lastseq = t[0]
					inter = config.getCollInterval (nodename, pl)
					v = (str (int (time.time ()) - len (m) * inter),)
					for tt in t[1:] :
							v += (tt,)
					val.append(v)
				self.db.minsert(nodename, pl, val)
				self.nodes[3][1][nodeno][plno] = lastseq

